package com.love.cloud.admin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMoziEmployeeListEmployeesByCodesResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.love.cloud.admin.api.entity.DingTalkDeptConfig;
import com.love.cloud.admin.api.entity.SysDept;
import com.love.cloud.admin.api.vo.DingTalkDeptInfoVo;
import com.love.cloud.admin.api.vo.DingTalkUserInfoVo;
import com.love.cloud.admin.api.vo.DingTalkUserTreeVo;
import com.love.cloud.admin.dto.DingTalkUserTreeDto;
import com.love.cloud.admin.dto.EmployeeSearchOrgDto;
import com.love.cloud.admin.mapper.DingTalkDeptConfigMapper;
import com.love.cloud.admin.mapper.SysDeptMapper;
import com.love.cloud.admin.service.DingTalkUserTreeService;
import com.love.cloud.common.core.exception.BusinessException;
import com.love.cloud.common.core.util.ModelMapperUtils;
import com.love.cloud.common.mybatis.util.PageUtils;
import com.love.cloud.common.zzd.api.GovDingAPICaller;
import com.love.cloud.common.zzd.dto.DingTalkEmployeePositionsDto;
import com.love.cloud.common.zzd.dto.DingTalkOrgDto;
import com.love.cloud.common.zzd.dto.DingTalkUserDto;
import com.love.cloud.common.zzd.dto.EmployeeSearchDto;
import com.love.cloud.common.zzd.properties.DingTalkProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author hongdongqu
 */
@Service
public class DingTalkUserTreeServiceImpl implements DingTalkUserTreeService {
    @Resource
    private DingTalkProperties dingTalkProperties;
    @Resource
    private GovDingAPICaller govDingAPICaller;
    @Resource
    private PageUtils pageUtils;
    @Resource
    private ModelMapperUtils modelMapperUtils;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private DingTalkDeptConfigMapper dingTalkDeptConfigMapper;

    @Override
    public DingTalkUserTreeDto getDeptAndUserInfo(DingTalkUserTreeVo dingTalkUserTreeVo) {
        //组织编码
        String orgCode="";
        if(StringUtils.isEmpty(dingTalkUserTreeVo.getOrgCode())){
            orgCode=dingTalkProperties.getRootOrgCode();
            //如果有传入限制的code，从数据库获取到对应的编码
            String configOrgCode = this.getConfigOrgCode(dingTalkUserTreeVo.getCascadeOrganizationCode());
            if(StringUtils.isNotEmpty(configOrgCode)){
                orgCode=configOrgCode;
            }
        }else{
            orgCode=dingTalkUserTreeVo.getOrgCode();
        }
        if(StringUtils.isEmpty(orgCode)){
            throw new BusinessException("请设置根节点的组织编码");
        }
        String type="all";
        if(StringUtils.isNotEmpty(dingTalkUserTreeVo.getType())){
            type=dingTalkUserTreeVo.getType();
        }
        DingTalkUserTreeDto dingTalkUserTreeDto=new DingTalkUserTreeDto();
        dingTalkUserTreeDto.setOrgCode(orgCode);
        //先获取部门列表
        if(type.contains("all")||type.contains("org")){
            List<DingTalkOrgDto> dingTalkOrgDtoList = govDingAPICaller.subOrganizationList(orgCode);
            dingTalkUserTreeDto.setOrgList(dingTalkOrgDtoList);
        }
        if(type.contains("all")||type.contains("user")){
            //获取到组织信息
            DingTalkOrgDto dingTalkOrgDto = govDingAPICaller.getOrgInfoByCode(orgCode);
            dingTalkUserTreeDto.setOrgName(dingTalkOrgDto.getOrganizationName());
            //再获取人员列表
            List<DingTalkUserDto> dingTalkUserDtoList = govDingAPICaller.organizationEmployeeList(orgCode);
            dingTalkUserTreeDto.setUserList(dingTalkUserDtoList);
        }
        return dingTalkUserTreeDto;
    }

    @Override
    public List<EmployeeSearchOrgDto> getUserInfo(DingTalkUserInfoVo dingTalkUserInfoVo) {
        //获取到配置部门信息
        String configOrgCode = this.getConfigOrgCode(dingTalkUserInfoVo.getCascadeOrganizationCode());
        if(StringUtils.isNotEmpty(configOrgCode)){
            dingTalkUserInfoVo.setCascadeOrganizationCode(configOrgCode);
        }
        //判断是否为手机号
        boolean isMobile = Pattern.matches("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[189]))\\d{8}$", dingTalkUserInfoVo.getNameKeywords());
        List<EmployeeSearchOrgDto> employeeSearchOrgDtoList=null;
        if(isMobile){
            employeeSearchOrgDtoList=new ArrayList<>();
            //通过手机号获取到浙政钉id
            String userData= govDingAPICaller.getUserInfoByMobile(dingTalkUserInfoVo.getNameKeywords());
            if(StringUtils.isNotEmpty(userData)){
                EmployeeSearchOrgDto employeeSearchOrgDto=new EmployeeSearchOrgDto();
                String employeeCode = govDingAPICaller.getUserParameter(userData, false, "employeeCode");
                String accountId = govDingAPICaller.getUserParameter(userData, false, "accountId");
                employeeSearchOrgDto.setAccountId(accountId);
                employeeSearchOrgDto.setEmployeeCode(employeeCode);
                List<String> codeList=new ArrayList<>();
                codeList.add(employeeCode);
                OapiMoziEmployeeListEmployeesByCodesResponse response = govDingAPICaller.listEmployeesByCodes(codeList);
                List<DingTalkUserDto> userList=null;
                if(response.getSuccess()||response.getContent().getSuccess()){
                    String data = response.getContent().getData();
                    userList=JSON.parseObject(data,new TypeReference<ArrayList<DingTalkUserDto>>(){});
                }
                if(userList!=null&&userList.size()>0){
                    DingTalkUserDto dingTalkUserDto=userList.get(0);
                    employeeSearchOrgDto.setEmployeeName(dingTalkUserDto.getEmployeeName());
                    this.setOrgInfo(employeeSearchOrgDto);
                    employeeSearchOrgDtoList.add(employeeSearchOrgDto);
                }
            }

        }else{
            //组织编码
            if(StringUtils.isEmpty(dingTalkUserInfoVo.getInOrganizationCode())&&StringUtils.isEmpty(dingTalkUserInfoVo.getCascadeOrganizationCode())){
                dingTalkUserInfoVo.setCascadeOrganizationCode(dingTalkProperties.getRootOrgCode());
            }
            List<EmployeeSearchDto> employeeSearchList = govDingAPICaller.searchEmployeeList(dingTalkUserInfoVo.getNameKeywords(), dingTalkUserInfoVo.getInOrganizationCode(), dingTalkUserInfoVo.getCascadeOrganizationCode());
            employeeSearchOrgDtoList = modelMapperUtils.toNewModelList(employeeSearchList, EmployeeSearchOrgDto.class);
            //查询组织信息
            for (EmployeeSearchOrgDto employeeSearchOrgDto :employeeSearchOrgDtoList) {
                boolean b = this.setOrgInfo(employeeSearchOrgDto);
            }
        }
        return employeeSearchOrgDtoList;
    }

    /**
     * 获取到配置的组织编码
     * @param cascadeOrganizationCode
     * @return
     */
    private String getConfigOrgCode(String cascadeOrganizationCode){
        String orgCode="";
        //如果有传入限制的code，从数据库获取到对应的编码
        if(StringUtils.isNotEmpty(cascadeOrganizationCode)){
            QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
            sysDeptQueryWrapper.lambda().eq(SysDept::getDingTalkId,cascadeOrganizationCode)
                    .last(" limit 1 ");
            SysDept sysDept = sysDeptMapper.selectOne(sysDeptQueryWrapper);
            if(sysDept!=null&&StringUtils.isNotEmpty(sysDept.getAsyncPathId())){
                String[] ids = sysDept.getAsyncPathId().split("/");
                QueryWrapper<DingTalkDeptConfig> deptConfigQueryWrapper=new QueryWrapper<>();
                deptConfigQueryWrapper.lambda().in(DingTalkDeptConfig::getOrgCode,ids)
                        .orderByDesc(DingTalkDeptConfig::getLevel)
                        .last(" limit 1 ");
                DingTalkDeptConfig dingTalkDeptConfig = dingTalkDeptConfigMapper.selectOne(deptConfigQueryWrapper);
                if(dingTalkDeptConfig!=null){
                    orgCode=dingTalkDeptConfig.getOrgCode();
                }
            }
        }
        return orgCode;
    }

    /**
     * 设置组织信息
     * @param employeeSearchOrgDto
     * @return
     */
    private boolean setOrgInfo(EmployeeSearchOrgDto employeeSearchOrgDto){
        // 注  此处浙政钉的接口返回的数据没有完整的数据,所以只能通过多个接口来获取
        List<DingTalkEmployeePositionsDto> positionsDtoList = govDingAPICaller.employeePositionsList(employeeSearchOrgDto.getEmployeeCode());
        if(positionsDtoList!=null&&positionsDtoList.size()>0){
            String orgCode=positionsDtoList.get(0).getOrganizationCode();
            List<String> orgList=new ArrayList<>();
            orgList.add(orgCode);
            employeeSearchOrgDto.setOrgCode(orgCode);
            //获取到组织的具体信息
            List<DingTalkOrgDto> orgListByCodes = govDingAPICaller.getOrgListByCodes(orgList);
            if(orgListByCodes!=null&&orgListByCodes.size()>0){
                employeeSearchOrgDto.setOrgName(orgListByCodes.get(0).getOrganizationName());
            }
            return true;
        }
        return false;
    }
    @Override
    public Object searchDingTalkDeptInfo(DingTalkDeptInfoVo dingTalkDeptInfoVo) {
        //组织编码
        if(StringUtils.isEmpty(dingTalkDeptInfoVo.getInOrganizationCode())&&StringUtils.isEmpty(dingTalkDeptInfoVo.getCascadeOrganizationCode())){
            dingTalkDeptInfoVo.setCascadeOrganizationCode(dingTalkProperties.getRootOrgCode());
        }else{
            String configOrgCode = this.getConfigOrgCode(dingTalkDeptInfoVo.getCascadeOrganizationCode());
            if(StringUtils.isNotEmpty(configOrgCode)){
                dingTalkDeptInfoVo.setCascadeOrganizationCode(configOrgCode);
            }
        }

        return govDingAPICaller.searchOrgList(dingTalkDeptInfoVo.getNameKeywords(),dingTalkDeptInfoVo.getInOrganizationCode(),dingTalkDeptInfoVo.getCascadeOrganizationCode());
    }

    @Override
    public Object getOrganizationLine(String organizationCode) {
        return govDingAPICaller.getOrganizationLine(organizationCode);
    }
}
